import { Footer } from '@/components';
import config from '@/config';
import { login } from '@/services/ant-design-pro/api';
import { getRestaurantList } from '@/services/ant-design-pro/desk';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, Helmet, history, SelectLang, useIntl, useModel } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(255, 255, 255, 0.6)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'all 0.3s ease',
      '&:hover': {
        color: '#fff',
        transform: 'scale(1.1)',
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 24,
      top: 24,
      borderRadius: token.borderRadius,
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      backdropFilter: 'blur(10px)',
      border: '1px solid rgba(255, 255, 255, 0.2)',
      transition: 'all 0.3s ease',
      '&:hover': {
        backgroundColor: 'rgba(255, 255, 255, 0.2)',
        transform: 'translateY(-2px)',
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      background: 'linear-gradient(135deg,rgb(234, 238, 255) 0%,rgb(170, 193, 255) 100%)',
      position: 'relative',
      '&::before': {
        content: '""',
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'url("data:image/svg+xml,%3Csvg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg"%3E%3Cg fill="none" fill-rule="evenodd"%3E%3Cg fill="%23ffffff" fill-opacity="0.1"%3E%3Ccircle cx="7" cy="7" r="1"/%3E%3Ccircle cx="27" cy="7" r="1"/%3E%3Ccircle cx="47" cy="7" r="1"/%3E%3Ccircle cx="7" cy="27" r="1"/%3E%3Ccircle cx="27" cy="27" r="1"/%3E%3Ccircle cx="47" cy="27" r="1"/%3E%3Ccircle cx="7" cy="47" r="1"/%3E%3Ccircle cx="27" cy="47" r="1"/%3E%3Ccircle cx="47" cy="47" r="1"/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")',
        opacity: 0.3,
      },
    },
    main: {
      flex: '1',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '32px 24px',
      position: 'relative',
      zIndex: 1,
    },
    loginCard: {
      background: 'rgba(255, 255, 255, 0.95)',
      backdropFilter: 'blur(20px)',
      borderRadius: '24px',
      padding: '48px 40px',
      boxShadow: '0 20px 60px rgba(0, 0, 0, 0.2)',
      border: '1px solid rgba(255, 255, 255, 0.3)',
      width: '100%',
      position: 'relative',
      maxWidth: '500px',
      '&::before': {
        content: '""',
        position: 'absolute',
        top: '-1px',
        left: '-1px',
        right: '-1px',
        bottom: '-1px',
        background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.1))',
        borderRadius: '24px',
        zIndex: -1,
      },
    },
    title: {
      fontSize: '32px',
      fontWeight: '700',
      textAlign: 'center',
      marginBottom: '8px',
      background: 'linear-gradient(135deg, #667eea, #764ba2)',
      backgroundClip: 'text',
      WebkitBackgroundClip: 'text',
      color: 'transparent',
    },
    subtitle: {
      fontSize: '16px',
      color: '#6b7280',
      textAlign: 'center',
      marginBottom: '32px',
      fontWeight: '400',
    },
    formItem: {
      marginBottom: '24px',
      '.ant-input': {
        borderRadius: '12px',
        fontSize: '16px',
        border: '2px solid #e5e7eb',
        transition: 'all 0.3s ease',
        '&:hover': {
          borderColor: '#667eea',
        },
        '&:focus': {
          borderColor: '#667eea',
          boxShadow: '0 0 0 3px rgba(102, 126, 234, 0.1)',
        },
      },
      '.ant-input-affix-wrapper': {
        height: '48px',
        borderRadius: '12px',
        fontSize: '16px',
        border: '2px solid #e5e7eb',
        transition: 'all 0.3s ease',
        '&:hover': {
          borderColor: '#667eea',
        },
        '&:focus-within': {
          borderColor: '#667eea',
          boxShadow: '0 0 0 3px rgba(102, 126, 234, 0.1)',
        },
      },
    },
    submitBtn: {
      '.ant-btn': {
        height: '48px',
        borderRadius: '12px',
        fontSize: '16px',
        fontWeight: '600',
        background: 'linear-gradient(135deg, #667eea, #764ba2)',
        border: 'none',
        transition: 'all 0.3s ease',
        '&:hover': {
          transform: 'translateY(-2px)',
          boxShadow: '0 8px 25px rgba(102, 126, 234, 0.3)',
        },
      },
    },
    tabs: {
      '.ant-tabs-nav': {
        marginBottom: '32px',
      },
      '.ant-tabs-tab': {
        fontSize: '16px',
        fontWeight: '500',
        color: '#6b7280',
        '&.ant-tabs-tab-active': {
          color: '#667eea',
          fontWeight: '600',
        },
      },
      '.ant-tabs-ink-bar': {
        background: 'linear-gradient(135deg, #667eea, #764ba2)',
        height: '3px',
        borderRadius: '2px',
      },
    },
    socialIcons: {
      display: 'flex',
      justifyContent: 'center',
      marginTop: '24px',
      padding: '16px 0',
      borderTop: '1px solid #e5e7eb',
    },
    alert: {
      borderRadius: '12px',
      border: 'none',
      backgroundColor: '#fef2f2',
      '.ant-alert-icon': {
        color: '#ef4444',
      },
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.socialIcons}>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </div>
  );
};

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  const { styles } = useStyles();
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      className={styles.alert}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const resp = await getRestaurantList({
      page: 1,
      pageSize: 50,
    });
    const storeOptions = resp?.data?.list?.map((item: any) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    localStorage.setItem('currentStoreId', storeOptions?.[0]?.value);
    window.MERCHANT_ID = storeOptions?.[0]?.value;

    flushSync(() => {
      setInitialState((s) => ({
        ...s,
        currentUser: {
          name: '管理员',
        },
        storeOptions,
      }));
    });
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values });
      if (msg.data.token) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        localStorage.setItem('token', msg.data.token);
        localStorage.setItem('refreshToken', msg.data.refreshToken);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/data');
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      {/* <Lang /> */}
      <div className={styles.main}>
        <div className={styles.loginCard}>
          <div className={styles.title}>{config.store.name}</div>
          
          <LoginForm
            contentStyle={{
              padding: 0,
              background: 'transparent',
              boxShadow: 'none',
            }}
            submitter={{
              render: (props) => {
                return (
                  <div className={styles.submitBtn}>
                    <button
                      className="ant-btn ant-btn-primary ant-btn-block"
                      style={{
                        width: '100%',
                        height: '48px',
                        borderRadius: '12px',
                        fontSize: '16px',
                        fontWeight: '600',
                        background: 'linear-gradient(135deg, #667eea, #764ba2)',
                        border: 'none',
                        color: '#fff',
                        cursor: 'pointer',
                        transition: 'all 0.3s ease',
                      }}
                      onClick={() => props.form?.submit?.()}
                    >
                      {intl.formatMessage({
                        id: 'pages.login.submit',
                        defaultMessage: '登录',
                      })}
                    </button>
                  </div>
                );
              },
            }}
            initialValues={{
              autoLogin: true,
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams);
            }}
          >

            {status === 'error' && loginType === 'account' && (
              <LoginMessage
                content={intl.formatMessage({
                  id: 'pages.login.accountLogin.errorMessage',
                  defaultMessage: '账户或密码错误',
                })}
              />
            )}
            
            {type === 'account' && (
              <>
                <div className={styles.formItem}>
                  <ProFormText
                    name="username"
                    fieldProps={{
                      size: 'large',
                      prefix: <UserOutlined style={{ color: '#9ca3af' }} />,
                    }}
                    placeholder={'请输入用户名'}
                    rules={[
                      {
                        required: true,
                        message: '请输入用户名',
                      },
                    ]}
                  />
                </div>
                <div className={styles.formItem}>
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined style={{ color: '#9ca3af' }} />,
                    }}
                    placeholder={'请输入密码'}
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.login.password.required"
                            defaultMessage="请输入密码！"
                          />
                        ),
                      },
                    ]}
                  />
                </div>
              </>
            )}

            {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
            {type === 'mobile' && (
              <>
                <div className={styles.formItem}>
                  <ProFormText
                    fieldProps={{
                      size: 'large',
                      prefix: <MobileOutlined style={{ color: '#9ca3af' }} />,
                    }}
                    name="mobile"
                    placeholder={intl.formatMessage({
                      id: 'pages.login.phoneNumber.placeholder',
                      defaultMessage: '手机号',
                    })}
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.login.phoneNumber.required"
                            defaultMessage="请输入手机号！"
                          />
                        ),
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: (
                          <FormattedMessage
                            id="pages.login.phoneNumber.invalid"
                            defaultMessage="手机号格式错误！"
                          />
                        ),
                      },
                    ]}
                  />
                </div>
                <div className={styles.formItem}>
                  <ProFormCaptcha
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined style={{ color: '#9ca3af' }} />,
                    }}
                    captchaProps={{
                      size: 'large',
                    }}
                    placeholder={intl.formatMessage({
                      id: 'pages.login.captcha.placeholder',
                      defaultMessage: '请输入验证码',
                    })}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count} ${intl.formatMessage({
                          id: 'pages.getCaptchaSecondText',
                          defaultMessage: '获取验证码',
                        })}`;
                      }
                      return intl.formatMessage({
                        id: 'pages.login.phoneLogin.getVerificationCode',
                        defaultMessage: '获取验证码',
                      });
                    }}
                    name="captcha"
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.login.captcha.required"
                            defaultMessage="请输入验证码！"
                          />
                        ),
                      },
                    ]}
                    onGetCaptcha={async (phone) => {
                      const result = await getFakeCaptcha({
                        phone,
                      });
                      if (!result) {
                        return;
                      }
                      message.success('获取验证码成功！验证码为：1234');
                    }}
                  />
                </div>
              </>
            )}
          </LoginForm>
          
          {/* <ActionIcons /> */}
        </div>
      </div>
      {/* <Footer /> */}
    </div>
  );
};

export default Login;
